import { Form, Upload, Button, } from 'antd';
import React, { useState, useEffect, createContext, useReducer } from 'react';
import styles from './index.less';
import DirsTable from './components/DirsTable';
import OptionsHeader from './components/OptionsHeader';
import { queryApiRule, shareRecords } from './service';
import BreadcrumbHeader from './components/BreadcrumbHeader';
import { filesUpload, beforeUpload } from "./components/OptionsHeader";
import GirdDirsTable from './components/girdDirsTable';
import { XS_SIZE, PATH_LENGTH, VDISK_NAME } from "@/generic/ConfigParams";

export const TableListContext = createContext();

const getVdiskName = (path = '') => {
  // console.log("===>>> getVdiskName is run !", path)
  switch (path) {
    case '/public/all':
      return 'pub';

    default:
      return 'usr';
      // return VDISK_NAME;  // 默认返回用户名
  }
}

const reducer = (state, action) => {  // 数据的统一处理
  // console.log("==+>> reducer", state, action)
  switch (action.type) {
    case 'loading':
      return action.value;
    case 'tableData':
      return action.data;
    default:
      return state;
  }
}

export const getTableData = async (params, disk = "pub", path = "") => {
  if (disk == 'usr' && path == '/') {
    path = `/${VDISK_NAME}`;
  }
  console.log('===>> path', path)
  const result = await queryApiRule(params, disk, path);
  console.log('===>> result.data', result.data)

  return result.data;
};

const getUpperLevel = (currentPath, vdisk) => {
  console.log("==>> getUpperLevel is run !", currentPath)
  let path = currentPath || "";
  if (path === "/" || path === "") {
    return;
  }
  let _path = path.split('/');
  console.log("==>> getUpperLevel", _path)
  _path.pop();
  // //usr
  // _path = _path.length > PATH_LENGTH ? _path.join("/") : "/";
  // console.log("==>> _path", _path, _path.split("/").pop())
  return _path.join("/");
}

const TableList = props => {

  const [batchOpts, setBatchOpts] = useState({ show: false, rows: [] });
  const [currentPath, setCurrentPath] = useState(props.location.state ? props.location.state.currentPath || '/' : '/');
  const [rowSize, setRowSize] = useState('default');
  const [listDisplay, setListDisplay] = useState(false);
  const [isMobile, setIsMobile] = useState(document.body.clientWidth < XS_SIZE ? true : false);

  const [loading, dpLoading] = useReducer(reducer, false);
  const [tableData, dpTableData] = useReducer(reducer, []);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);

  const _vdisk = () => getVdiskName(props.match.path);

  useEffect(()=> {
    console.log("==>>> localStorage", localStorage)
  }, [])

  useEffect(() => {

    document.body.clientWidth < XS_SIZE ? setIsMobile(true) : setIsMobile(false);
  }, [document.body.clientWidth])

  useEffect(() => {
    dpLoading({ type: 'loading', value: true });
    setSelectedRowKeys([]);
  }, [tableData])

  useEffect(() => {
    console.log("====>> this.currentPath !", currentPath);
    dpTableData({ type: 'tableData', data: getTableData({}, _vdisk(), currentPath) });
  }, [currentPath])

  const contextOpts = {
    loading: { param: loading, dispatch: dpLoading },
    tableData: { param: tableData, dispatch: dpTableData },
  }

  const rowSelection = {

    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => { // _:占位符
      setSelectedRowKeys(selectedRowKeys);
      if (selectedRows && selectedRows.length > 0) {
        setBatchOpts({ show: true, rows: selectedRows });
        return;
      }
      setBatchOpts({ show: false, rows: [] });
    },
  }

  const { Dragger } = Upload;

  const tableRefresh = () => {

    dpTableData({ type: 'tableData', data: getTableData({}, _vdisk(), currentPath) })
  }

  const draggerProps = {
    className: styles.dragger,
    openFileDialogOnClick: false,
    showUploadList: false,
    beforeUpload,
    customRequest: (file) => filesUpload(file, _vdisk(), currentPath, tableRefresh),
  };

  const shareProps = {
    currentPath: currentPath,
    vdisk: _vdisk,
    tableRefresh: tableRefresh
  };

  return (
    <TableListContext.Provider value={contextOpts}>
      <OptionsHeader
        className={styles.headerOptions}
        batchOpts={batchOpts}
        listDisplay={listDisplay}
        onSearch={(newData) => {
          console.log("===>> newData", newData)
          dpTableData({ type: 'tableData', data: newData });
        }}
        {...shareProps}
      />

      <BreadcrumbHeader
        className={styles.pageHeader}
        isMobile={isMobile}
        locationName={props.route.name}
        onBack={() => setCurrentPath(getUpperLevel(currentPath, _vdisk))}
        onItemClick={(e, path = "/") => {
          e.preventDefault();
          setCurrentPath(path);
        }}
        setRowSize={setRowSize}
        setListDisplay={() => setListDisplay(!listDisplay)}
        listDisplay={listDisplay}
        {...shareProps}
      />
      <Dragger {...draggerProps}>
        {
          listDisplay && (
            <DirsTable
              response={tableData}
              isMobile={isMobile}
              rowSelection={!isMobile ? rowSelection : undefined}
              batchOpts={batchOpts}
              onNameClick={(record) => setCurrentPath(record.path)}
              onRow={(record, key) => {
                return {
                  onDoubleClick: event => setCurrentPath(record.path),
                }
              }}
              rowSize={rowSize}
              {...props}
              {...shareProps}
            />
          )
        }
        {
          !listDisplay && (
            <GirdDirsTable
              data={tableData}
              onGridItem={(record) => {
                return {
                  onClick: () => { console.log("==>> record", record);setCurrentPath(record.path)},
                }
              }}
              {...props}
              {...shareProps}
            />
          )
        }
      </Dragger>
    </TableListContext.Provider>
  )
}

export default Form.create()(TableList);
